<template>
  <div class="job-statistics-test">
    <div class="test-header">
      <el-card>
        <div class="header-content">
          <h2>岗位统计API测试页面</h2>
          <p>测试岗位统计接口的数据获取和图表展示</p>
          <div class="test-controls">
            <el-button type="primary" @click="testBasicStatistics" :loading="loading">
              测试基础统计
            </el-button>
            <el-button type="success" @click="testDetailedStatistics" :loading="loading">
              测试详细统计
            </el-button>
            <el-button @click="clearResults">
              清空结果
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- API测试结果 -->
    <div class="test-results" v-if="testResults.length > 0">
      <el-card v-for="(result, index) in testResults" :key="index" class="result-card">
        <template #header>
          <div class="result-header">
            <span class="api-name">{{ result.name }}</span>
            <el-tag :type="result.success ? 'success' : 'danger'">
              {{ result.success ? '成功' : '失败' }}
            </el-tag>
          </div>
        </template>
        
        <div class="result-content">
          <div class="api-info">
            <p><strong>接口地址:</strong> {{ result.url }}</p>
            <p><strong>响应时间:</strong> {{ result.responseTime }}ms</p>
            <p><strong>状态码:</strong> {{ result.status }}</p>
          </div>
          
          <div class="data-preview" v-if="result.success && result.data">
            <h4>返回数据预览:</h4>
            <div class="data-summary">
              <div v-if="result.data.jobs" class="data-section">
                <h5>岗位统计:</h5>
                <ul>
                  <li>总数: {{ result.data.jobs.total }}</li>
                  <li>已发布: {{ result.data.jobs.published }}</li>
                  <li>草稿: {{ result.data.jobs.draft }}</li>
                  <li>已关闭: {{ result.data.jobs.closed }}</li>
                  <li>已过期: {{ result.data.jobs.expired }}</li>
                </ul>
              </div>
              
              <div v-if="result.data.applications" class="data-section">
                <h5>申请统计:</h5>
                <ul>
                  <li>总数: {{ result.data.applications.total }}</li>
                  <li>待审核: {{ result.data.applications.pending }}</li>
                  <li>已通过: {{ result.data.applications.approved }}</li>
                  <li>已拒绝: {{ result.data.applications.rejected }}</li>
                  <li>成功率: {{ result.data.applications.success_rate }}%</li>
                </ul>
              </div>
              
              <div v-if="result.data.companies" class="data-section">
                <h5>公司统计:</h5>
                <ul>
                  <li>总数: {{ result.data.companies.total }}</li>
                  <li>活跃公司: {{ result.data.companies.active_companies?.length || 0 }}</li>
                </ul>
              </div>
            </div>
            
            <details class="json-details">
              <summary>查看完整JSON数据</summary>
              <pre class="json-preview">{{ JSON.stringify(result.data, null, 2) }}</pre>
            </details>
          </div>
          
          <div class="error-info" v-if="!result.success">
            <h4>错误信息:</h4>
            <p class="error-message">{{ result.error }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据可视化测试 -->
    <div class="visualization-test" v-if="chartData.length > 0">
      <el-card>
        <template #header>
          <h3>数据可视化测试</h3>
        </template>
        
        <div class="charts-test-grid">
          <div class="chart-test-item" v-for="chart in chartData" :key="chart.name">
            <h4>{{ chart.name }}</h4>
            <div class="chart-container">
              <v-chart :option="chart.option" style="height: 250px;" />
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 性能测试 -->
    <div class="performance-test" v-if="performanceData.length > 0">
      <el-card>
        <template #header>
          <h3>性能测试结果</h3>
        </template>
        
        <el-table :data="performanceData" border>
          <el-table-column prop="api" label="接口" />
          <el-table-column prop="responseTime" label="响应时间(ms)" />
          <el-table-column prop="dataSize" label="数据大小" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { ElMessage } from 'element-plus'
import { jobApi } from '@/api/jobs'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const loading = ref(false)
const testResults = ref<any[]>([])
const chartData = ref<any[]>([])
const performanceData = ref<any[]>([])

// 测试基础统计API
const testBasicStatistics = async () => {
  loading.value = true
  try {
    const startTime = Date.now()
    const response = await jobApi.getJobStatistics()
    const endTime = Date.now()
    
    const result = {
      name: '基础岗位统计',
      url: '/api/jobs/statistics/',
      success: true,
      status: 200,
      responseTime: endTime - startTime,
      data: response.data
    }
    
    testResults.value.push(result)
    
    // 添加性能数据
    performanceData.value.push({
      api: '基础统计',
      responseTime: result.responseTime,
      dataSize: JSON.stringify(response.data).length + ' bytes',
      status: 'success'
    })
    
    // 创建图表
    createChartsFromBasicData(response.data)
    
    ElMessage.success('基础统计测试成功')
  } catch (error: any) {
    const endTime = Date.now()
    testResults.value.push({
      name: '基础岗位统计',
      url: '/api/jobs/statistics/',
      success: false,
      status: error.response?.status || 0,
      responseTime: endTime - Date.now(),
      error: error.message
    })
    
    performanceData.value.push({
      api: '基础统计',
      responseTime: 'N/A',
      dataSize: 'N/A',
      status: 'error'
    })
    
    ElMessage.error('基础统计测试失败')
  } finally {
    loading.value = false
  }
}

// 测试详细统计API
const testDetailedStatistics = async () => {
  loading.value = true
  try {
    const startTime = Date.now()
    const response = await jobApi.getDetailedJobStatistics({ period: 'month' })
    const endTime = Date.now()
    
    const result = {
      name: '详细岗位统计',
      url: '/api/jobs/statistics/detailed/',
      success: true,
      status: 200,
      responseTime: endTime - startTime,
      data: response.data
    }
    
    testResults.value.push(result)
    
    // 添加性能数据
    performanceData.value.push({
      api: '详细统计',
      responseTime: result.responseTime,
      dataSize: JSON.stringify(response.data).length + ' bytes',
      status: 'success'
    })
    
    // 创建图表
    createChartsFromDetailedData(response.data)
    
    ElMessage.success('详细统计测试成功')
  } catch (error: any) {
    const endTime = Date.now()
    testResults.value.push({
      name: '详细岗位统计',
      url: '/api/jobs/statistics/detailed/',
      success: false,
      status: error.response?.status || 0,
      responseTime: endTime - Date.now(),
      error: error.message
    })
    
    performanceData.value.push({
      api: '详细统计',
      responseTime: 'N/A',
      dataSize: 'N/A',
      status: 'error'
    })
    
    ElMessage.error('详细统计测试失败')
  } finally {
    loading.value = false
  }
}

// 从基础数据创建图表
const createChartsFromBasicData = (data: any) => {
  if (data.jobs) {
    chartData.value.push({
      name: '岗位状态分布',
      option: {
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '50%',
          data: [
            { value: data.jobs.published, name: '已发布' },
            { value: data.jobs.draft, name: '草稿' },
            { value: data.jobs.closed, name: '已关闭' },
            { value: data.jobs.expired, name: '已过期' }
          ]
        }]
      }
    })
  }
  
  if (data.job_types) {
    chartData.value.push({
      name: '岗位类型分布',
      option: {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: data.job_types.map((item: any) => item.job_type)
        },
        yAxis: { type: 'value' },
        series: [{
          type: 'bar',
          data: data.job_types.map((item: any) => item.count)
        }]
      }
    })
  }
}

// 从详细数据创建图表
const createChartsFromDetailedData = (data: any) => {
  if (data.trends?.job_publication) {
    chartData.value.push({
      name: '岗位发布趋势',
      option: {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: data.trends.job_publication.map((item: any) => item.date)
        },
        yAxis: { type: 'value' },
        series: [{
          type: 'line',
          data: data.trends.job_publication.map((item: any) => item.count)
        }]
      }
    })
  }
  
  if (data.distributions?.salary) {
    chartData.value.push({
      name: '薪资分布',
      option: {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: data.distributions.salary.map((item: any) => item.range)
        },
        yAxis: { type: 'value' },
        series: [{
          type: 'bar',
          data: data.distributions.salary.map((item: any) => item.count)
        }]
      }
    })
  }
}

// 清空结果
const clearResults = () => {
  testResults.value = []
  chartData.value = []
  performanceData.value = []
  ElMessage.info('测试结果已清空')
}
</script>

<style lang="scss" scoped>
.job-statistics-test {
  .test-header {
    margin-bottom: 24px;
    
    .header-content {
      h2 {
        margin: 0 0 8px 0;
        color: var(--text-color-primary);
      }
      
      p {
        margin: 0 0 16px 0;
        color: var(--text-color-secondary);
      }
      
      .test-controls {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .test-results {
    display: grid;
    gap: 16px;
    margin-bottom: 24px;
    
    .result-card {
      .result-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .api-name {
          font-weight: 600;
          color: var(--text-color-primary);
        }
      }
      
      .result-content {
        .api-info {
          margin-bottom: 16px;
          
          p {
            margin: 4px 0;
            font-size: 14px;
          }
        }
        
        .data-summary {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 16px;
          margin-bottom: 16px;
          
          .data-section {
            h5 {
              margin: 0 0 8px 0;
              color: var(--text-color-primary);
            }
            
            ul {
              margin: 0;
              padding-left: 16px;
              
              li {
                margin: 4px 0;
                font-size: 14px;
              }
            }
          }
        }
        
        .json-details {
          summary {
            cursor: pointer;
            font-weight: 600;
            margin-bottom: 8px;
          }
          
          .json-preview {
            background: var(--fill-color-light);
            padding: 12px;
            border-radius: 4px;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
          }
        }
        
        .error-message {
          color: var(--color-danger);
          font-size: 14px;
        }
      }
    }
  }
  
  .visualization-test {
    margin-bottom: 24px;
    
    .charts-test-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 24px;
      
      .chart-test-item {
        h4 {
          margin: 0 0 12px 0;
          color: var(--text-color-primary);
          text-align: center;
        }
        
        .chart-container {
          height: 250px;
        }
      }
    }
  }
  
  .performance-test {
    .el-table {
      margin-top: 16px;
    }
  }
}
</style>
